<?php

namespace App\Http\Controllers;

use App;
use App\Wechat;
use Cache;
use Carbon\Carbon;

class WechatService {
  use CurlTrait;

  public function getToken() {
    $token = Cache::get('accessToken');

    if (empty($token)) {
      if (isset($token)) {
        $token->delete();
      }
      $wechat_config = App::make('config')->get('services.wechat', []);
      extract($wechat_config);

      $token = $this->curlCallGet('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret);
      $token = json_decode($token, true);
      
      $expiresAt = Carbon::now()->addHours(2);
      Cache::put('accessToken', $token['access_token'], $expiresAt);

      return $token['access_token'];
    } else {
      return $token;
    }
  }
}